import { useState, useEffect, useMemo } from "react";
import {
  ScrollView,
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
} from "react-native";
import { getStorageData, setStorageData } from "utils";
import { useAppSelector } from "app/store";
import dayjs from "dayjs";
import { Dimensions } from "react-native";
import translate from "utils/translate";

const wp = Dimensions.get("screen").width / 392;
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"total">) => {
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const [List, setList] = useState<
    {
      goodsName: string;
      price: string;
      total: number;
      nums: string;
      checked?: boolean;
      createTime: number;
    }[]
  >([]);
  useEffect(() => {
    getStorageData("totalList").then((value) => {
      const isEmpty = Object.getOwnPropertyNames(params).length === 0;
      const List = value ? JSON.parse(value) : [];
      if (!isEmpty) {
        List.unshift(params);
      }
      setList(List);
    });
  }, []); // 将 route.params 作为依赖项传递

  useEffect(() => {
    return () => {
      // 在组件卸载时保存数据
      setStorageData("totalList", JSON.stringify(List));
    };
  }, [List]); // 将 List 作为依赖项传递
  const [checkAll, setCheckAll] = useState(false);
  const onSubmit = () => {
    getStorageData("saleList").then(async (value) => {
      const saleList = value ? JSON.parse(value) : [];
      const index = saleList.findIndex(
        (item) => item.deviceId == connectedDevice
      );
      const formatList = List.map((item) => {
        const {
          checked,
          total: amount,
          nums: count,
          createTime,
          ...rest
        } = item;
        return {
          ...rest,
          amount,
          count,
          createTime: dayjs(createTime).format("YYYY-MM-DD HH:mm:ss"),
        };
      });
      if (index !== -1) {
        saleList.splice(index, 1, {
          ...List[index],
          sale: [...formatList, ...saleList[index].sale],
        });
      } else {
        const value = await getStorageData("bleList");
        const name = value
          ? JSON.parse(value).find((item) => item.uuid == connectedDevice)?.name
          : translate("main.WeighingApparatus");
        saleList.unshift({
          sale: formatList,
          deviceId: connectedDevice,
          name,
        });
      }
      setStorageData("saleList", JSON.stringify(saleList)).then(() => {
        setList(() => []);
        navigation.goBack();
      });
    });
  };
  const total = useMemo(() => {
    return List.reduce((pre, cur) => {
      return pre + Number(cur.total);
    }, 0);
  }, [List]);
  return (
    <>
      <View
        style={{
          justifyContent: "space-around",
          flexDirection: "row",
          width: 343,
          alignSelf: "center",
          marginTop: 10,
        }}
      >
        <Text style={{ fontSize: 20, fontWeight: "600", color: "red" }}>
          {translate("main.CumulativeFrequency")}：
          <Text>{List?.length ?? 0}</Text>
        </Text>
        <Text style={{ fontSize: 20, fontWeight: "600", color: "red" }}>
          {translate("main.AccumulatedAmount")}：<Text>{total.toFixed(2)}</Text>
        </Text>
      </View>
      <ScrollView
        style={{
          flex: 1,
        }}
        contentContainerStyle={{
          alignItems: "center",
          marginTop: 12.5,
          paddingBottom: 12.5,
        }}
      >
        {List.map((item) => {
          return (
            <View style={styles.item} key={item.createTime}>
              <Text
                style={{
                  borderBottomColor: "#F0F0F0",
                  borderBottomWidth: 1,
                  paddingBottom: 5,
                  paddingTop: 10,
                }}
              >
                {item.goodsName}
              </Text>
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  justifyContent: "space-between",
                  paddingTop: 5,
                }}
              >
                <View>
                  <Text
                    style={{
                      fontSize: 20,
                      fontWeight: "700",
                      color: "#333333",
                    }}
                  >
                    {item.nums}
                  </Text>
                  <Text>{translate("main.NetWeight")}</Text>
                </View>
                <View>
                  <Text
                    style={{
                      fontSize: 20,
                      fontWeight: "700",
                      color: "#333333",
                    }}
                  >
                    {item.price}
                  </Text>
                  <Text>{translate("class.price")}</Text>
                </View>
                <View>
                  <Text
                    style={{
                      fontSize: 20,
                      fontWeight: "700",
                      color: "#EE1D1D",
                    }}
                  >
                    {item.total}
                  </Text>
                  <Text>{translate("main.amount")}</Text>
                </View>
                <TouchableOpacity
                  onPress={() => {
                    item.checked = !item.checked;
                    setList((pre) => {
                      return [...pre];
                    });
                  }}
                >
                  <Image
                    style={{
                      width: 24,
                      height: 24,
                    }}
                    source={
                      item.checked
                        ? require("assets/images/checked.png")
                        : require("assets/images/unchecked.png")
                    }
                  ></Image>
                </TouchableOpacity>
              </View>
            </View>
          );
        })}
      </ScrollView>
      <View
        style={{
          flexDirection: "row",
          backgroundColor: "#fff",
          bottom: 0,
          width: "100%",
          paddingVertical: 12,
          alignItems: "center",
          justifyContent:'center'
        }}
      >
        <TouchableOpacity
          style={{
            ...styles.button,
            backgroundColor: "#0181FE",
            borderColor: "#0181FE",
            borderTopRightRadius: 0,
            borderBottomRightRadius: 0,
          }}
          onPress={onSubmit}
        >
          <Text
            style={{
              color: "#FFFFFF",
            }}
          >
            {translate("main.payment")}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{
            ...styles.button,
            backgroundColor: "rgba(1, 129, 254, 0.1)",
            borderColor: "#0181FE",
            borderTopLeftRadius: 0,
            borderBottomLeftRadius: 0,
          }}
          onPress={() => {
            navigation.goBack();
          }}
        >
          <Text
            style={{
              color: "#0181FE",
            }}
          >
            {translate("main.Back")}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{
            ...styles.button,
            borderColor: "#D9001B",
            marginLeft: 30 * wp,
          }}
          onPress={() => {
            setList(List.filter((item) => !item.checked));
            setCheckAll(false);
          }}
        >
          <Text
            style={{
              color: "#D9001B",
            }}
          >
            {translate("main.delete")}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            setCheckAll(!checkAll);
            setList(
              List.map((item) => {
                const { checked, ...rest } = item;
                return {
                  ...rest,
                  checked: !checkAll,
                };
              })
            );
          }}
          style={{
            alignItems: "center",
            marginLeft: 16 * wp,
          }}
        >
          <Image
            style={{
              width: 24,
              height: 24,
            }}
            source={
              checkAll
                ? require("assets/images/checked.png")
                : require("assets/images/unchecked.png")
            }
          ></Image>
          <Text
            style={{
              fontSize: 12 * wp,
            }}
          >
            {translate("main.All")}
          </Text>
        </TouchableOpacity>
      </View>
    </>
  );
};
const styles = StyleSheet.create({
  item: {
    backgroundColor: "#fff",
    width: 343,
    paddingHorizontal: 20,
    borderRadius: 12,
    paddingBottom: 12,
    marginBottom: 12,
  },
  button: {
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 25 * wp,
    paddingVertical: 9,
    borderWidth: 1,
    borderRadius: 4,
  },
});
